<?php

namespace App\Http\Controllers;

use App\Models\Swiper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SwiperController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:sanctum')->except('index');
    }

    public function index(Request $request)
    {
        $swiper = Swiper::query();
        $swiper->when($request->filled('name'), function ($query) use ($request) {
            $name = $request->input('name');
            return $query->where('name', 'like', "%$name%");
        });

        $data = $swiper->orderBy('order')->get();
        return $this->success('查询成功', $data);
    }

    public function show(Swiper $swiper)
    {
        $this->authorize('viewAny', $swiper);
        return $this->success('添加成功', $swiper);
    }

    public function store(Request $request, Swiper $swiper)
    {
        $this->authorize('viewAny', $swiper);
        Validator::make($request->input(), [
            'image' => ['required'],
            'status' => ['required'],
        ])->validate();
        $swiper->fill($request->input());
        $swiper->save();
        return $this->success('添加成功', $swiper);
    }

    public function update(Request $request, Swiper $swiper)
    {
        $this->authorize('viewAny', $swiper);
        Validator::make($request->input(), [
            'image' => ['required'],
            'status' => ['required'],
        ])->validate();
        $swiper->fill($request->input());
        $swiper->save();
        return $this->success('更新成功', $swiper);
    }

    public function destroy(Request $request, Swiper $swiper)
    {
        $this->authorize('viewAny', $swiper);
        $swiper->delete();
        return $this->success('删除成功', $swiper);
    }
}
